package com.ueboot.weishop.admin.batch.tasklet;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ueboot.core.exception.BusinessException;
import com.ueboot.core.utils.DateUtils;
import com.ueboot.weishop.entity.order.OrderEnum;
import com.ueboot.weishop.entity.order.OrderIssueEntity;
import com.ueboot.weishop.service.order.OrderIssueService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SendDmsStepThirdTasklet implements Tasklet {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private OrderIssueService issueService;

	public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
		List<OrderIssueEntity> issueList = issueService.findBySendDmsStatus(OrderEnum.SEND_STATUS_0);

		if (issueList.size() < 1) {
			logger.info("下发DMS优惠券跑批任务 step third DMS代金券发送DMS结束......发送条数：0条，不发送DMS");
			return RepeatStatus.FINISHED;
		}
		List<Map<String, String>> mapReqList = Lists.newLinkedList();
		issueList.forEach(issue -> {
			Map<String, String> reqMap = new HashMap<String, String>();
			reqMap.put("SEQ_NO", issue.getSeqNo());
			reqMap.put("NAME", issue.getName());
			reqMap.put("VIN", issue.getVin());
			reqMap.put("CAMPAIGN_CODE", issue.getCampaignCode());
			reqMap.put("VALID_BEGIN_DATE", issue.getValidBeginDate());
			reqMap.put("VALID_END_DATE", issue.getValidEndDate());
			reqMap.put("TARGET_DEALER", issue.getTargetDealer());//需要查询数据库获得得到经销商代码
			reqMap.put("USE_DEALER", "");
			reqMap.put("AMOUNT", issue.getAmount());
			reqMap.put("USE_AMOUNT", "0.0");
			reqMap.put("LOWEST_AMOUNT", StringUtils.isEmpty(issue.getLowestAmount()) ? "0.0" : issue.getLowestAmount());
			reqMap.put("LIMIT_DEDUCT", issue.getAmount());
			reqMap.put("IS_CANCEL", OrderIssueEntity.CANCER_0);
			mapReqList.add(reqMap);
		});
		String responseMessage;
		try {
			responseMessage = issueService.sendDmsCoupon(mapReqList);
		} catch (BusinessException e) {
			logger.error("调用DMS数据异常！{}", e.getMessage(), e);
			return RepeatStatus.FINISHED;
		}
		Map dmsResp = JSON.parseObject(responseMessage, Map.class);

		if (dmsResp==null|| !"OK".equals(dmsResp.get("code"))) {
			logger.info("DMS回传接口异常！FC不做任何处理！{}", dmsResp.get("message"));
			return RepeatStatus.FINISHED;
		}
		Map dmsRespBoy = JSON.parseObject(dmsResp.get("body") + "", Map.class);
		if (!"0".equals(dmsRespBoy.get("status_code"))) {
			logger.info("DMS回传接口返回数据异常！FC不做任何处理！{}", JSON.toJSON(dmsRespBoy));
			throw new BusinessException("DMS回传接口返回数据异常！FC不做任何处理！");
		}
		List<Map<String, String>> contentMapList = (List<Map<String, String>>) dmsRespBoy.get("content");
		Date nowDate = new Date();
		for (OrderIssueEntity issue : issueList) {
			issue.setLastSendDmsTime(nowDate);
			issue.setSendDmsStatus(OrderEnum.SEND_STATUS_2);
			issue.setDmsResult("发送失败");
			issue.setCancel("0");
			Integer sendCount = issue.getSendDmsCount();
			if (sendCount == null) {
				sendCount = 0;
			}
			issue.setSendDmsCount(sendCount + 1);
			String sendHistory = issue.getSendDmsHistory();
			if (sendHistory == null) {
				sendHistory = "";
			}
			if (contentMapList == null || contentMapList.size() == 0) {
				issue.setSendDmsStatus(OrderEnum.SEND_STATUS_2);
				issue.setDmsResult("发送成功");
				sendHistory += "【发送时间：" + DateUtils.format(new Date(), DateUtils.FORMAT_DATE_TIME_DEFAULT) + "，第" + (sendCount + 1) + "次发送，Cancer:0,发送结果：发送成功】";
			} else {
				for (Map<String, String> mapContent : contentMapList) {
					if (issue.getVin().equals(mapContent.get("VIN")) && issue.getSeqNo().equals(mapContent.get("SEQ_NO"))) {
						issue.setDmsResult(mapContent.get("ERROR_MSG"));
						sendHistory += "【发送时间：" + DateUtils.format(new Date(), DateUtils.FORMAT_DATE_TIME_DEFAULT) + "，第" + (sendCount + 1) + "次发送，Cancer:0，发送结果：" + mapContent.get("ERROR_MSG") + "】";
						break;
					}
				}
			}
			issue.setSendDmsHistory(sendHistory);
		}
		issueService.updateAll(issueList);
		logger.info("下发DMS优惠券跑批任务 step third DMS代金券发送DMS结束......发送条数：{}", mapReqList.size());
		return RepeatStatus.FINISHED;

	}
}
